
package dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import tables.RouteTable;

import com.epam.grsulab.webapi.dao.AbstractDao;

import entity.Route;

public class RouteDao extends AbstractDao<RouteTable, Route> {

	public RouteDao(final String rootFolderPath) {
		super(rootFolderPath);
	}

	@Override
	public void saveNew(final Route newRoute) {
		newRoute.setId(getNextId());
		final RouteTable table = deserializeFromXml();
		table.getRows().add(newRoute);
		serializeToXml(table);
	}

	@Override
	public void update(final Route entity) {
		final RouteTable table = deserializeFromXml();
		for (final Route row : table.getRows()) {
			if (row.getId().equals(entity.getId())) {
				// found!!!
				// copy data
				row.setStart(entity.getStart());
				row.setEnd(entity.getEnd());
				break;
			}
		}
		serializeToXml(table);
	}

	@Override
	public Route get(final Serializable id) {
		final RouteTable table = deserializeFromXml();
		for (final Route row : table.getRows()) {
			if (row.getId().equals(id)) {
				return row;
			}
		}
		return null;
	}

	@Override
	public List<Route> getAll() {
		final RouteTable table = deserializeFromXml();
		return table.getRows();
	}

	@Override
	public void delete(final Serializable id) {
		final RouteTable table = deserializeFromXml();
		Route toBeDeleted = null;
		for (final Route row : table.getRows()) {
			if (row.getId().equals(id)) {
				toBeDeleted = row;
				break;
			}
		}
		table.getRows().remove(toBeDeleted);
		serializeToXml(table);
	}
	
	@Override
	protected Class<RouteTable> getTableClass() {
		return RouteTable.class;
	}
}
